/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.enumerated;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

import org.zhiqim.kernel.constants.CodeConstants;

/**
 * DES/AES加密模式枚举类型
 *
 * @version v1.0.0 @author zhichenggang 2017-3-25 新建与整理
 */
public enum CipherMode implements CodeConstants
{
    /*****************************************************************************/
    //枚举类型定义
    /*****************************************************************************/
    
    /** 电码本（基本的模式） */
    ECB,
    
    /** 密文分组链接模式 */
    CBC;
    
    /*****************************************************************************/
    //枚举调用方法
    /*****************************************************************************/
    
    /**
     * 初始化加密密码器，CBC模式下需要初始化向量
     * 
     * @param cipher                                密码器
     * @param secretKey                             密钥
     * @throws InvalidKeyException                  非法的密钥键
     * @throws InvalidAlgorithmParameterException   非法的算法参数
     */
    public void initCipherEncrypt(Cipher cipher, SecretKey secretKey) throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        if (this == ECB)
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        else
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(secretKey.getEncoded()));
    }
    
    /**
     * 初始化解密密码器，CBC模式下需要初始化向量
     * 
     * @param cipher                                密码器
     * @param secretKey                             密钥
     * @throws InvalidKeyException                  非法的密钥键
     * @throws InvalidAlgorithmParameterException   非法的算法参数
     */
    public void initCipherDecrypt(Cipher cipher, SecretKey secretKey) throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        if (this == ECB)
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
        else
            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(secretKey.getEncoded()));
    }
    
    @Override
    public String toString()
    {
        return (this == ECB)?_ECB_:_CBC_;
    }
}
